<template>
  <div>
    <Card class="smart-query-card">
      <!------ 查询条件第一行 begin------->
      <Row class="smart-query-form-row">
        <span>
          名称 :
          <Input
            placeholder="请输入名称"
            style="width: 180px"
            v-model="queryForm.name"
          />
        </span>

        <ButtonGroup>
          <Button
            @click="queryList"
            icon="ios-search"
            type="primary"
            v-privilege="'driving-cycle-list-query'"
            >查询</Button
          >
          <Button
            @click="resetQueryList"
            icon="md-refresh"
            type="default"
            v-privilege="'driving-cycle-list-query'"
            >重置</Button
          >
        </ButtonGroup>
      </Row>
      <Row class="smart-query-form-row" justify="space-between">
        <Col span="12">
          <Button
            @click="showAddDrivingCycleForm"
            icon="md-add"
            type="primary"
            v-privilege="'driving-cycle-list-add'"
            >新建数据</Button
          >
        </Col>
        <Col span="12">
          <Button
            :loading="allExportBtnLoading"
            @click="queryMyList"
            class="marginLeft10 float-right"
            type="primary"
            v-privilege="'driving-cycle-list-export-all'"
            >查询我的数据</Button
          >
        </Col>
      </Row>
      <!------ 查询条件第一行 begin------->
    </Card>
    <Card class="warp-card">
      <!-------操作按钮行 begin------->

      <Row class="card_top" justify="space-between">
        <!-- <Col span="12" push="0.2">
          发动机部件库
        </Col>
        <Col span="11" class="col_right">
          共收录 <span style="color:red">{{ mainTablePage.total }}</span> 款产品
        </Col> -->
        <Col span="8" push="3">
          图片
        </Col>
        <Col span="13" push="2">
          规格型号
        </Col>
        <Col span="3" push="0.2">
          操作
        </Col>
      </Row>
      <!-------操作按钮行 end------->
      <!-------表格列表 begin------->
      <div style="background-color:#f2f2f2">
        <Row
          v-for="(item, index) in mainTable.data"
          class="table-row"
          justify="space-between"
          :key="item"
          style="background-color:#fff"
        >
          <!-- <Col span="12" push="0.2">
          发动机部件库
        </Col>
        <Col span="11" class="col_right">
          共收录 <span style="color:red">{{ mainTablePage.total }}</span> 款产品
        </Col> -->
          <Col span="7" push="1">
            <div style="width:60%">
              <viewer :images="item.image">
                <img
                  style="width:100%;height:160px"
                  :src="
                    item.image
                      ? item.image
                      : 'https://img0.baidu.com/it/u=699973849,3290692557&fm=26&fmt=auto'
                  "
                  alt=""
                />
              </viewer>
            </div>
          </Col>
          <Col span="4" push="">
            <Row style="display:inline;line-height:40px">
              <Col :lg="6" :xs="24">名称：</Col>
              <Col :lg="18" :xs="24">{{ item.name }}</Col>
            </Row>
          </Col>
          <Col span="10" push="">
            <div>时间：{{ item.time }}</div>
            <div style="margin-top:10px">车速(km/h)：{{ item.speed }}</div>
            <div style="margin-top:10px">载荷(kg)：{{ item.load }}</div>
            <div style="margin-top:10px">坡度(%)：{{ item.gradient }}</div>
          </Col>
          <Col span="2" push="0.2" style="color:#2D8cF0">
            <div @click="showDetail(item)" class="tab-button">
              详情
            </div>
            <div
              style="margin-top:20px"
              @click="showEditDrivingCycleForm(item)"
              class="tab-button"
              v-if="item.createUser == myUserId"
            >
              修改
            </div>
          </Col>
          <Col span="1" pull="0.5">
            <Icon
              v-if="item.createUser == myUserId"
              @click="deletedSure(item.id)"
              type="ios-trash-outline"
              style="font-size:20px"
              class="tab-button"
            />
          </Col>
        </Row>
      </div>
      <Row class="" justify="center">
        <Page
          :current="queryForm.pageNum"
          :page-size="queryForm.pageSize"
          :page-size-opts="mainTablePage.pageSizeOps"
          :total="mainTablePage.total"
          @on-change="changeMainTablePagePageNum"
          @on-page-size-change="changeMainTablePagePageSize"
          class="smart-query-table-page"
          show-elevator
          show-sizer
          show-total
        />
      </Row>
    </Card>

    <!-------批量删除Modal begin------->
    <Modal title="批量删除" v-model="batchDeleteModal.show" width="450">
      <Form :label-width="80">
        <FormItem>
          <h3 class="error-color">确定要删除以下数据吗？</h3>
        </FormItem>
        <FormItem label="删除数据">
          <Card style="width:350px;height:250px;overflow-y:scroll;">
            <ul>
              <li v-for="item in mainTableSelectArray">
                <a href="#">{{ item.id }}</a>
              </li>
            </ul>
          </Card>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          @click="batchDeleteModal.show = false"
          size="small"
          type="default"
          >取消</Button
        >
        <Button @click="batchDelete" size="small" type="primary"
          >确定删除</Button
        >
      </div>
    </Modal>
    <!-------批量删除Modal end------->

    <!-------添加、更新 Form表单 begin------->
    <Modal
      :footer-hide="true"
      :title="saveModal.isUpdate ? '修改' : '新建'"
      v-model="saveModal.show"
      @on-cancel="saveFormClose"
      width="500"
    >
      <DrivingCycleListForm
        :isUpdate="saveModal.isUpdate"
        :updateData="saveModal.updateData"
        @on-form-close="saveFormClose"
        ref="child"
      />
    </Modal>
    <!-------添加、更新 Form表单 end------->

    <!-------详情 begin------->
    <Modal
      :footer-hide="true"
      title="详情"
      v-model="detailModal.show"
      @on-cancel="detailModal.show = false"
      width="500"
    >
      <DrivingCycleListDetail
        :isUpdate="saveModal.isUpdate"
        :updateData="saveModal.updateData"
        @on-form-close="detailModal.show = false"
      />
    </Modal>
    <!-------详情 end------->
  </div>
</template>

<script>
import { dateTimeRangeConvert } from "@/lib/util";
import { PAGE_SIZE_OPTIONS } from "@/constants/table-page";
import { drivingCycleApi } from "@/api/driving-cycle";
import DrivingCycleListForm from "./components/driving-cycle-list-form";
import DrivingCycleListDetail from "./components/driving-cycle-list-detail";
const PAGE_SIZE_INIT = 20;
export default {
  name: "DrivingCycleList",
  components: {
    DrivingCycleListForm,
    DrivingCycleListDetail
  },
  props: {},
  data() {
    return {
      /* -------------------------详情 ------------------------- */
      detailModal: {
        show: false,
        isUpdate: false,
        updateData: null
      },
      /* -------------------------批量操作------------------------- */
      /* -------------------------添加、更新表单 ------------------------- */
      saveModal: {
        show: false,
        isUpdate: false,
        updateData: null
      },
      /* -------------------------批量操作------------------------- */
      //批量刪除彈出框
      batchDeleteModal: {
        show: false
      },
      //表格多选选中的元素数组
      mainTableSelectArray: [],
      /* -------------------------导出操作------------------------- */
      //批量导出loading按钮
      batchExportBtnLoading: false,
      //导出全部loading按钮
      allExportBtnLoading: false,
      /* -------------------------查询条件相关数据-------------------- */
      //搜索表单
      queryForm: {
        //名称
        name: null,
        //创建人
        createUser: null,
        createTimeRange: ["", ""],
        updateTimeRange: ["", ""],
        pageNum: 1,
        pageSize: PAGE_SIZE_INIT,
        orders: []
      },
      //是否展示更多搜索条件
      showMoreQueryConditionFlag: false,
      /*  -------------------------表格相关数据------------------------- */
      //表格分页
      mainTablePage: {
        total: 0,
        pageSizeOps: PAGE_SIZE_OPTIONS
      },
      //表格
      mainTable: {
        //加载中
        loading: false,
        //表格数据
        data: [],
        //表格列
        columnArray: [
          {
            title: "序号",
            key: "id",
            tableColumn: "t_driving_cycle.id",
            sortable: "custom"
          },
          {
            title: "名称",
            key: "name",
            tableColumn: "t_driving_cycle.name",
            sortable: "custom"
          },
          {
            title: "时间",
            key: "time",
            tableColumn: "t_driving_cycle.time",
            sortable: "custom"
          },
          {
            title: "车速(km/h)",
            key: "speed",
            tableColumn: "t_driving_cycle.speed",
            sortable: "custom"
          },
          {
            title: "载荷(kg)",
            key: "load",
            tableColumn: "t_driving_cycle.load",
            sortable: "custom"
          },
          {
            title: "坡度(%)",
            key: "gradient",
            tableColumn: "t_driving_cycle.gradient",
            sortable: "custom"
          },
          {
            title: "操作",
            key: "action",
            align: "right",
            width: 130,
            className: "action-hide",
            render: (h, params) => {
              let actions = [
                {
                  title: "详情",
                  directives: [
                    {
                      name: "privilege",
                      value: "driving-cycle-list-query"
                    }
                  ],
                  action: () => {
                    this.saveModal.isUpdate = true;
                    this.saveModal.updateData = params.row;
                    this.detailModal.show = true;
                  }
                },
                {
                  title: "编辑",
                  directives: [
                    {
                      name: "privilege",
                      value: "driving-cycle-list-update"
                    }
                  ],
                  action: () => {
                    this.showEditDrivingCycleForm(params.row);
                  }
                },
                ,
                {
                  title: "删除",
                  directives: [
                    {
                      name: "privilege",
                      value: "driving-cycle-list-update"
                    }
                  ],
                  action: () => {
                    this.$Modal.confirm({
                      title: "友情提醒",
                      content: "确定要删除吗？",
                      onOk: () => {
                        this.deleteById(params.row.id);
                      }
                    });
                  }
                }
              ];
              return this.$tableAction(h, actions);
            }
          }
        ]
      },
      myUserId: null
    };
  },
  computed: {},
  watch: {},
  filters: {},
  created() {
    this.myUserId = this.$store.state.user.userLoginInfo.id;
  },
  mounted() {
    this.queryList();
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
  methods: {
    deletedSure(id) {
      this.$Modal.confirm({
        title: "友情提醒",
        content: "确定要删除吗？",
        onOk: () => {
          this.deleteById(id);
        }
      });
    },
    showDetail(row) {
      this.id = row.id;
      this.$router.push({
        path: "/driving-cycle/driving-cycle-detail",
        query: { id: row.id }
      });
    },
    async deleteById(id) {
      this.$Spin.show();
      this.mainTableSelectArray.push(id);
      await drivingCycleApi.batchDeleteDrivingCycle(this.mainTableSelectArray);
      this.$Message.success("刪除成功");
      this.mainTableSelectArray = [];
      this.$Spin.hide();
      this.queryList();
    },
    queryMyList() {
      this.queryForm.createUser = 1;
      this.queryList();
    },
    /* -------------------------查询相关 begin------------------------- */
    convertQueryParam() {
      let createTimeArray = dateTimeRangeConvert(
        this.queryForm.createTimeRange
      );
      let updateTimeArray = dateTimeRangeConvert(
        this.queryForm.updateTimeRange
      );
      return {
        ...this.queryForm,
        createTimeBegin: createTimeArray[0],
        createTimeEnd: createTimeArray[1],
        updateTimeBegin: updateTimeArray[0],
        updateTimeEnd: updateTimeArray[1]
      };
    },
    //查询
    async queryList() {
      this.mainTable.loading = true;
      try {
        let params = this.convertQueryParam();
        let result = await drivingCycleApi.queryDrivingCycle(params);
        this.mainTable.data = result.data.list;
        this.mainTablePage.total = result.data.total;
      } finally {
        this.mainTable.loading = false;
      }
    },
    //重置查询
    resetQueryList() {
      let pageSize = this.queryForm.pageSize;
      this.queryForm = {
        name: null,
        createUser: null,
        createTimeRange: ["", ""],
        updateTimeRange: ["", ""],
        pageNum: 1,
        pageSize: pageSize,
        orders: []
      };
      this.queryList();
    },
    //修改页码
    changeMainTablePagePageNum(pageNum) {
      this.queryForm.pageNum = pageNum;
      this.queryList();
    },
    //修改页大小
    changeMainTablePagePageSize(pageSize) {
      this.queryForm.pageNum = 1;
      this.queryForm.pageSize = pageSize;
      this.queryList();
    },
    //处理排序
    handleSortChange(column) {
      if (column.order === "normal") {
        this.queryForm.orders = [];
      } else {
        this.queryForm.orders = [
          {
            column: column.column.tableColumn,
            asc: "asc" === column.order
          }
        ];
      }
      this.queryList();
    },
    /*-------------------------查询相关 end------------------------- */

    /*-------------------------批量操作 begin------------------------- */
    //显示批量删除弹窗
    showBatchDeleteModal() {
      if (!this.validateMainTableSelection()) {
        return;
      }
      this.batchDeleteModal.show = true;
    },
    //批量删除
    async batchDelete() {
      this.$Spin.show();
      await drivingCycleApi.batchDeleteDrivingCycle(
        this.mainTableSelectArray.map(e => e.id)
      );
      this.batchDeleteModal.show = false;
      this.$Message.success("刪除成功");
      this.$Spin.hide();
      this.queryList();
    },
    //清空选中
    clearMainTableSelection() {
      this.mainTableSelectArray = [];
    },
    //校验是否有选中
    validateMainTableSelection() {
      this.mainTableSelectArray = this.$refs.mainTable.getSelection();
      if (this.mainTableSelectArray.length < 1) {
        this.$Message.error("请选择至少一条数据");
        return false;
      }
      return true;
    },
    /*-------------------------批量操作 end------------------------- */

    /*-------------------------导入导出 begin------------------------- */
    //导出全部
    async exportAll() {
      try {
        this.allExportBtnLoading = true;
        let params = this.convertQueryParam();
        await drivingCycleApi.exportAll(params);
      } catch (e) {
        console.log(e);
      } finally {
        this.allExportBtnLoading = false;
      }
    },
    //批量导出
    async batchExport() {
      if (!this.validateMainTableSelection()) {
        return;
      }
      try {
        this.batchExportBtnLoading = true;
        await drivingCycleApi.batchExport(
          this.mainTableSelectArray.map(e => e.id)
        );
      } catch (e) {
        console.log(e);
      } finally {
        this.batchExportBtnLoading = false;
      }
    },
    /*-------------------------导入导出 end------------------------- */

    /*-------------------------添加，修改 表单 begin------------------------- */
    //显示添加表单
    showAddDrivingCycleForm() {
      this.saveModal.isUpdate = false;
      this.saveModal.show = true;
    },
    showEditDrivingCycleForm(updateObject) {
      this.saveModal.isUpdate = true;
      this.saveModal.updateData = updateObject;
      this.saveModal.show = true;
    },
    saveFormClose() {
      this.$refs.child.resetForm();
      this.saveModal.show = false;
      this.queryList();
    }
    /*-------------------------添加，修改 表单 end------------------------- */
  }
};
</script>
<style lang="less">
.ivu-row {
  display: flex;
  align-items: center;
}
.card_top {
  border: none;
  margin: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 39px;
  background-color: rgba(242, 242, 242, 1);
}
.table-row {
  min-height: 220px;
  font-size: 14px;
  margin-bottom: 10px;
  padding-right: 10px;
}
.col_right {
  display: flex;
  justify-content: flex-end;
}
.tab-button {
  cursor: pointer;
}
</style>
